package com.level.system.task;

import com.alibaba.fastjson.JSON;
import com.level.system.entity.emr.DATA_HZ;
import com.level.system.service.EmrParseService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.*;

public class HZ_MZBLThread extends Thread {

    private List<DATA_HZ> dsList;
    private EmrParseService emrService;

    public HZ_MZBLThread(List<DATA_HZ> list, EmrParseService service) {
        this.dsList = list;
        this.emrService = service;
    }

    @Override
    public void run() {
        handleTask(this.dsList);
    }


    private void handleTask(List<DATA_HZ> list) {
        List<Map<String, Object>> paramList = new ArrayList<Map<String, Object>>();
        Map<String, Object> paramMap = new HashMap<String, Object>();

        for (Iterator it = list.iterator(); it.hasNext(); ) {
            // 1获取病历对象
            DATA_HZ emrParser = (DATA_HZ) it.next();
            // 2获取病历html
            String html = new String(emrParser.getMRCONTENT());
            // 3获取病历解析结果
            Map<String, Object> map = getMzbl(html);
            map.put("jgid", emrParser.getJGID());
            map.put("id", emrParser.getID());
            map.put("mcNo", emrParser.getMCNO());
            map.put("docId", emrParser.getDOCID());
            map.put("mzzy", emrParser.getMZZY());
            map.put("emrType", emrParser.getEMRTYPE());
            map.put("measureDate", emrParser.getMEASUREDATE());
            map.put("archiveTime", emrParser.getARCHIVETIME());
            map.put("rysj", emrParser.getRYSJ());
            map.put("cysj", emrParser.getCYSJ());

            map.put("name", emrParser.getNAME());
            map.put("sex", emrParser.getSEX());
            map.put("birthday", emrParser.getBIRTHDAY());

            map.put("creater", "dba");
            map.put("createTime", new Date());


            paramList.add(map);
        }
        paramMap.put("list", paramList);
        emrService.batchSaveMzbl(paramMap);
    }

    /**
     * 获取门诊病历
     *
     * @param html
     * @return
     */
    public Map<String, Object> getMzbl(String html) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("state", "0");

        // 病历文书内容
        Document doc = Jsoup.parseBodyFragment(html);
        // 获取所有符合条件的标签域

        //1体格检查基本元素
        Elements elements = doc.select("span[levelplugins='element']");
        for (Iterator it = elements.iterator(); it.hasNext(); ) {
            Element element = (Element) it.next();
            // 获取有level-model属性的span
            Elements simples = element.select("span[level-model]");
            for (int k = 0; k < simples.size(); k++) {
                Element simple = simples.get(k);
                String levelModel = simple.attr("level-model");
                // 转成map对象
                Map<String, Object> modelMap = JSON.parseObject(levelModel);
                // 获取默认值属性
                String elementId = modelMap.get("elementId").toString();
                if ("BE-1002-1002-1004".equals(elementId)) {
                    // 门诊 血压值（收缩压）（mmHg)
                    map.put("sbp", getMRElementXmlText(element));
                } else if ("BE-1002-1002-1005".equals(elementId)) {
                    //  门诊 血压值（舒张压）（mmHg)
                    map.put("dbp", getMRElementXmlText(element));
                } else if ("BE-1002-1002-1001".equals(elementId)) {
                    // 门诊 体温（℃）
                    map.put("temperature", getMRElementXmlText(element));
                } else if ("BE-1002-1002-1002".equals(elementId)) {
                    //门诊 心率（次/分）
                    map.put("heartrate", getMRElementXmlText(element));
                } else if ("BE-1002-1002-1003".equals(elementId)) {
                    //门诊 呼吸（次/分）
                    map.put("breathrate", getMRElementXmlText(element));
                } else if ("BE-1002-1002-1006".equals(elementId)) {
                    //门诊 身高（cm）
                    map.put("height", getMRElementXmlText(element));
                } else if ("BE-1002-1002-1007".equals(elementId)) {
                    //门诊 体重（kg）
                    map.put("weight", getMRElementXmlText(element));
                }
            }
        }
        //  2主诉、现病史章节元素
        Elements lcs = doc.select("span[levelchapter]");
        for (Iterator it = lcs.iterator(); it.hasNext(); ) {
            Element lc = (Element) it.next();
            String levelchapter = lc.attr("levelchapter");
            // 转成map对象
            Map<String, Object> chapterMap = JSON.parseObject(levelchapter);
            // 获取默认值属性
            String chapterId = chapterMap.get("chapterId").toString();
            if ("MR-1009-1001-1001".equals(chapterId)) {
                // 主诉
                map.put("chiefcomplaint", getMRXmlText(lc));
            } else if ("MR-1009-1001-1002".equals(chapterId)) {
                // 现病史
                map.put("medicalhistory", getMRXmlText(lc));
            }
        }
        return map;
    }

    /**
     * 获取基本元素内容
     *
     * @param element
     * @return
     */
    private static String getMRElementXmlText(Element element) {
        //1替换空格2提取leftbrackets、rightbrackets节点内容
        String tempHtml = element.html();
        tempHtml = tempHtml.replaceAll("&nbsp;", "");
        element.html(tempHtml);

        String text = element.text().trim();
        if (text.length() > 0) {
            // 去掉[
            text = text.substring(1, text.length());
            // 去掉]
            if (text.length() > 0) {
                text = text.substring(0, text.length() - 1);
            }
        }
        return text.trim();
    }

    /**
     * 获取章节元素内容
     *
     * @param element
     * @return
     */
    private static String getMRXmlText(Element element) {
        String levelchapter = element.attr("levelchapter");
        Map<String, Object> chapterMap = JSON.parseObject(levelchapter);
        // 获取默认值属性
        String chapterId = chapterMap.get("chapterId").toString();
        // 1移除levelplugins=nodeblock
        element.select("span[levelplugins='nodeblock']").remove();
        // 2提取leftbrackets、rightbrackets节点内容

        // 替换空格
        String tempHtml = element.html();
        tempHtml = tempHtml.replaceAll("&nbsp;", " ");
        element.html(tempHtml);

        String text = element.text().trim();
        // System.out.println("element.html " + element.html());
        if (text.length() > 0) {
            // 去掉[
            text = text.substring(1, text.length());
            // 去掉]
            if (text.length() > 0) {
                text = text.substring(0, text.length() - 1);
            }
        }
        // System.out.println("chapterId " + chapterMap);
        // System.out.println("text " + text);
        return text.trim();
    }
}
